import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Modal, Card, Spin, message, Table, Input} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, PAGE, TABLE, FIXED_COLUMN_WIDTH, FORM_ROW_OPTIONS} from '../constants';
import {uuid, conventEnumValueToString, exportDownload} from '../utils';
import {PERMISSION, dealerConditions} from './constants';
import WrappedSelect from '../common/WrappedSelect';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import {validateAdd, generateRowSpanData} from './utils';
import Return from '../common/Return';
import ClaimSelectPanel from './ClaimSelectPanel';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import {getDealerSimple, getDealers, exportUsedPartDestory} from './api';
import TextInput from 'Shared/components/TextInput';
import {currency} from '../Enum';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const {Search} = Input;
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPanel: false,
        isSearch: false,
        searchPartCode: ''
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name, e) => {
        const {applyid, id} = e.target.dataset;
        const data = {
            value,
            claimId: applyid,
            id,
            isDetailsRemark: true
        };
        this.props.onConditionsChange(name, data);
    }
    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    };
    onClickExportBtn = () => {
        this.setState({loading: true});
        exportUsedPartDestory(this.props.id).then(res => {
            this.setState({loading: false});
            exportDownload(res.data);
        });
    }
    onClickDelete = e => {
        const {id, applyid, uid} = e.target.dataset;
        this.setState({
            hasOperat: true,
            currentApplyId: '',
        });
        this.props.onDeleteDetail({
            uid,
            id,
            claimId: applyid
        });
    };

    onSelectClaim = (data = EMPTY_ARRAY, isAll) => {
        this.props.onSelectClaim(data, isAll);
    };

    onSubmit = () => {
        const result = validateAdd(this.props.conditions, this.props.id);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onClickAddDetail = () => {
        if(this.state.isSearch)
            return message.warn(this.props.intl.formatMessage({
                id: 'add.onClickAddIsSearch.message',
                defaultMessage: '请先取消筛选清单'
            }));
        if(!this.props.id && !this.props.conditions.dealerId)
            return message.warn(this.props.intl.formatMessage({
                id: 'add.onClickAddDetail.message',
                defaultMessage: '请先选择总代'
            }));
        this.setState({showPanel: true});
    }

    onSelectDealer = data => {
        const {dealerId, details = []} = this.props.conditions;
        if(!data.id || data.id === dealerId) return;
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(dealerId && details.length)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'add.onSelectDealer.title',
                    defaultMessage: '变更总代，将会清空清单，是否清空？'
                }),
                onOk: () => {
                    this.props.onSelectDealer(data);
                }
            });
        else
            this.props.onSelectDealer(data);
    }
    
    handleReset = clearFilters => {
        clearFilters();
        this.setState({searchText: ''});
    };

    onSearchClaim = value => {
        const {details} = this.props.conditions;
        if(!details.length)
            return message.warn(this.props.intl.formatMessage({
                id: 'add.onClickSearchDetail.message',
                defaultMessage: '请先增加清单'
            }));
        this.props.onSearch(value);
        this.setState({isSearch: true});
    }
    onDeleteAll = () => {
        this.props.onIsSearch({
            isSearch: false,
            newDetails: []
        });
        this.setState({
            isSearch: false,
            searchPartCode: ''
        });
        this.props.onDeleteAll();
    }
    onChangeCodeValue = e => {
        this.setState({
            searchPartCode: e.target.value
        });
        if(!e.target.value.length) {
            this.props.onIsSearch({
                isSearch: false,
                newDetails: []
            });
            this.setState({isSearch: false});
        }
    }
    render() {
        const {details = EMPTY_ARRAY} = this.props.conditions;
        const {isSearch, newDetails} = this.props.searchDetails;
        const currentSelectRowKeys = details.map(item => item.claimId);
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.claimCode',
                    defaultMessage: '索赔单号'
                }),
                dataIndex: 'claimCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.supplierCode',
                    defaultMessage: '供应商编号'
                }),
                dataIndex: 'supplierCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.subDealerCode',
                    defaultMessage: '经销商编号'
                }),
                dataIndex: 'subDealerCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.subDealerName',
                    defaultMessage: '经销商名称'
                }),
                dataIndex: 'subDealerName',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.subClaimCode',
                    defaultMessage: '经销商申请单号'
                }),
                dataIndex: 'subClaimCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.usedPartBarCode',
                    defaultMessage: '旧件条码'
                }),
                dataIndex: 'usedPartBarCode',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.usedPartCode',
                    defaultMessage: '备件号'
                }),
                dataIndex: 'usedPartCode'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.usedPartName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'usedPartName',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.unit',
                    defaultMessage: '单位'
                }),
                dataIndex: 'unit',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
                render: (text, record) => (
                    <FormItem required>
                        <TextInput
                            name="remark"
                            data-applyid={record.claimId}
                            data-id={record.id}
                            value={record.remark}
                            onBlur={this.onChange}/>
                    </FormItem>
                )
            }, {
                title: details.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onDeleteAll}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onClickDelete} key="delete" data-id={record.usedPartBarCode} data-applyid={record.claimId} data-uid={record.id}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];
        if(!this.props.isDealerUser)
            columns.splice(4, 0, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.claimSignedRemark',
                    defaultMessage: '索赔标记备注'
                }),
                dataIndex: 'claimSignedRemark',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text ? record.rowSpan : 0,
                    },
                })
            });
        const dealerInfo = this.props.conditions.dealerId ? {
            id: this.props.conditions.dealerId,
            code: this.props.conditions.dealerCode,
            name: this.props.conditions.dealerName
        } : null;
        const queryCondition = {
            ...dealerConditions,
            brandId: this.props.conditions.brandId
        };
        const dealerComp = this.props.conditions.brandId ? (<DealerSelectPanel
            allowClear={false}
            value={dealerInfo}
            getDealerSimple={getDealerSimple}
            getDealers={getDealers}
            conditions={queryCondition}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled placeholder={this.props.intl.formatMessage({
                id: 'add.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.claimModal.title',
                        defaultMessage: '维修索赔单查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <ClaimSelectPanel
                        brandId={this.props.conditions.brandId}
                        dealerId={this.props.conditions.dealerId}
                        currentSelectRowKeys={currentSelectRowKeys}
                        onSelect={this.props.onSelectClaim}
                        afterSubmit={this.showPanel} />
                </Modal>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            title={this.props.intl.formatMessage({
                                id: 'add.card.title',
                                defaultMessage: '基本信息'
                            })}>
                            <Row>
                                <Col key="code" {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.code',
                                            defaultMessage: '编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.id ? this.props.conditions.code : this.props.intl.formatMessage({
                                            id: 'add.form.code.noData',
                                            defaultMessage: '<尚未生成>'
                                        })}</span>
                                    </FormItem>
                                </Col>
                                {this.props.brands.length > 1 ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.brandId ? 'error' : null}
                                        required={!this.props.id}>
                                        {this.props.id ? <span className="value-font">{this.props.conditions.brandCode}</span>
                                            : <WrappedSelect
                                                name="brandId"
                                                value={this.props.conditions.brandId}
                                                options={this.props.brands}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col> : null}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.dealerId ? 'error' : null}
                                        required={!this.props.id}
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id ? <span className="value-font">{this.props.conditions.dealerCode}</span>
                                            : dealerComp}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.currency',
                                            defaultMessage: '币种'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{conventEnumValueToString(currency, this.props.conditions.currency)}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !this.props.conditions.remark ? 'error' : null}
                                    required>
                                        <TextInput
                                            name="remark"
                                            value={this.props.conditions.remark}
                                            onBlur={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={<Row>
                                <Col {...FORM_OPTIONS.col}>
                                    {this.props.intl.formatMessage({
                                        id: 'add.details',
                                        defaultMessage: '销毁单清单'
                                    })}
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.searchPartCode',
                                        defaultMessage: '备件号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        <Search
                                            placeholder="输入多个值时，请按逗号隔开"
                                            onSearch={this.onSearchClaim}
                                            value={this.state.searchPartCode}
                                            allowClear
                                            onChange={this.onChangeCodeValue}
                                            className={styles.minScreenSearchWidth}/>
                                    </FormItem>
                                </Col>
                            </Row>}
                            extra={<div>
                                {details.length > 0 && <Button onClick={this.onClickExportBtn} size="small">
                                    {this.props.intl.formatMessage({
                                        id: 'add.btn.export',
                                        defaultMessage: '导出'
                                    })}
                                </Button>}
                                <Button onClick={this.onClickAddDetail} size="small">
                                    {this.props.intl.formatMessage({
                                        id: 'add.btn.add',
                                        defaultMessage: '新增'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="index"
                                columns={columns}
                                pagination={false}
                                dataSource={isSearch ? newDetails : details}
                                {...TABLE} />
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    brands: PropTypes.array.isRequired,
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onDeleteAll: PropTypes.func.isRequired,
    onDeleteDetail: PropTypes.func.isRequired,
    onSelectClaim: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onSubmit,
    getEditInitData,
    selectClaim,
    deleteAllDetail,
    deleteDetail,
    selectDealerForAdd,
    isSearch,
    onSearch
} from './actions';
import {createSelector} from 'reselect';

const getSubmitData = createSelector(
    state => state.getIn(['page', 'appState', 'submitData']),
    data => {
        const conditions = data.toJS() || {};
        const {details = [], ...props} = conditions;
        const newDetails = generateRowSpanData(details, 'claimId', ['claimCode', 'claimSignedRemark', 'subDealerCode', 'subDealerName', 'subClaimCode']);
        return {
            ...props,
            details: newDetails.map(item => ({
                id: item.id || uuid(),
                ...item,
            }))
        };
    }
);

const getNewDetailsData = createSelector(
    state => state.getIn(['page', 'appState', 'searchDetails']),
    data => {
        const conditions = data.toJS() || {};
        const {newDetails = [], ...props} = conditions;
        const details = generateRowSpanData(newDetails, 'claimId', ['claimCode', 'claimSignedRemark', 'subDealerCode', 'subDealerName', 'subClaimCode']);
        return {
            ...props,
            newDetails: details.map(item => ({
                id: item.id || uuid(),
                ...item,
            }))
        };
    }
);

const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    brands => {
        const data = brands.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            value: item.id,
            text: item.name
        }));
    }
);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
    brands: getBrands(state),
    searchDetails: getNewDetailsData(state)
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInitData(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onSubmit(ownProps.id, ownProps.isSubmit)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onSelectClaim: (data, isAll) => dispatch(selectClaim(data, isAll)),
    onSelectDealer: data => dispatch(selectDealerForAdd(data)),
    onDeleteAll: () => dispatch(deleteAllDetail()),
    onDeleteDetail: data => dispatch(deleteDetail(data)),
    onIsSearch: data => dispatch(isSearch(data)),
    onSearch: data => dispatch(onSearch(data))
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
